﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Services;
using System.Web.UI.WebControls;
using Foothill.Common;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.Exceptions;
using Foothill.Service.Session;
using Foothill.Service.UserAccount;

namespace Foothill.Web
{
    // partial class definition of ForSaleList, contains code merely for UI
    public partial class ForSaleList : FoothillBasePage
    {
        // handles bind the ad instance to each row
        protected void gvwAdList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow) 
            {
                ForSaleAd post = e.Row.DataItem as ForSaleAd;

                SetupAdHyperlink(e.Row, post);

                SetupSavePost(e.Row, post);

                DisplayAdSummary(e.Row, post);

                DisplayProfilePicture(e.Row, post);

                DisplayMileageAndPrice(e.Row, post);

                DisplayCityAndPostDate(e.Row, post);

                DisplayUserLogo(e.Row, post);
            }
        }

        // Make, Model, and year
        private void DisplayAdSummary(GridViewRow row, ForSaleAd post)
        {
            Label lblVehicleType = row.FindControl("lblVehicleType") as Label;
            lblVehicleType.Text = post.GetVehicleTypeString();
        }

        private void SetupAdHyperlink(GridViewRow row, ForSaleAd post)
        {
            string url = string.Format("~/ForSaleAdDetail/ForSaleAdDetail.aspx?{0}={1}&{2}=1", GlobalQueryString.AdDetailsQsName, post.AdId, GlobalQueryString.FromSearchListQsName);
            HyperLink link = row.FindControl("hlkAdTitle") as HyperLink;
            link.NavigateUrl = url;

            link = row.FindControl("hlkProfilePic") as HyperLink;
            link.NavigateUrl = url;
        }

        private void SetupSavePost(GridViewRow row, ForSaleAd post)
        {
            HyperLink link = row.FindControl("hlkSavePost") as HyperLink;
            Image imgSaved = row.FindControl("imgSaved") as Image;

            if (link != null)
            {
                if (_currentLoginUserId > 0)
                {
                    link.NavigateUrl = string.Format("{0}#{1}#{2}", _currentLoginUserId, post.AdId, imgSaved.ClientID);
                    link.Visible = _currentLoginUserId != post.PostedByUserAccountId && currentUser.SavedPostIdList.All(i => i != post.AdId);
                    if (link.Visible)
                    {
                        imgSaved.CssClass = "imgSaved-hide";
                    }
                }
                else
                {
                    link.Visible = false;
                    imgSaved.Visible = false;
                }
            }
        }

        protected void SavePostClick(object sender, EventArgs e)
        {
            LinkButton savePostBtn = sender as LinkButton;

            if (savePostBtn != null)
            {
                GridViewRow row = savePostBtn.NamingContainer as GridViewRow;

                int postId = (int)gvwAdList.DataKeys[row.RowIndex].Value;

                _userAccountService.SavePost(_securityService.GetLoginUserId(), postId);
            }
        }

        [WebMethod]
        public static void SavePost(int userId, int postId)
        {
            if (userId > 0 && postId > 0)
            {
                IUserAccountService userAccountService = IocContainer.GetInstance<IUserAccountService>();

                try
                {
                    userAccountService.SavePost(userId, postId);
                    ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
                    
                    CurrentLoginUser currentUser = sessionService.GetSessionValue(SessionNames.LoginUser) as CurrentLoginUser;

                    if (currentUser != null)
                    {
                        if (!currentUser.SavedPostIdList.Contains(postId))
                        {
                            currentUser.SavedPostIdList.Add(postId);
                        }
                    }
                }
                catch (FailToSavePostException e)
                {
                }
            }
        }

        private void DisplayProfilePicture(GridViewRow row, ForSaleAd post)
        {
            Image imgProfile = row.FindControl("imgProfile") as Image;

            if (imgProfile != null)
            {
                // if there is no profile photo, the ProfilePhotoPath will be empty
                if (!string.IsNullOrEmpty(post.ProfilePhotoPath)) 
                {
                    string path = Path.Combine(GlobalSettings.ThumbnailFolder, Path.GetFileName(post.ProfilePhotoPath));

                    if (File.Exists(Server.MapPath(path)))
                    {
                        imgProfile.ImageUrl = path;
                        return;
                    }
                }

                // display "Photo Not Available" 
                imgProfile.ImageUrl = GlobalSettings.PhotoNotAvailablePath;
            }
        }

        private void DisplayMileageAndPrice(GridViewRow row, ForSaleAd post)
        {
            Label lblPrice = row.FindControl("lblPrice") as Label;
            lblPrice.Text = string.Format("${0}", post.Price.ToString());
        }

        private void DisplayCityAndPostDate(GridViewRow row, ForSaleAd post)
        {
            Label lblCity = row.FindControl("lblCity") as Label;
            lblCity.Text = post.CityName;

            Label lblPostDate = row.FindControl("lblPostDate") as Label;
            lblPostDate.Text = post.TimePosted.Date.ToShortDateString();
        }

        private void DisplayUserLogo(GridViewRow row, ForSaleAd post)
        {
            Image imgLogo = row.FindControl("imgLogo") as Image;

            if (imgLogo != null)
            {
                if (string.IsNullOrWhiteSpace(post.PostedUserLogoFilePath))
                {
                    imgLogo.Visible = false;
                }
                else
                {
                    imgLogo.ImageUrl = _userAccountService.GetLogoFileUrl(post.PostedUserLogoFilePath);
                }           
            }
        }

        private void DisplayStatsItem(GridViewRowEventArgs e, string cbxControlName, string lblControlName)
        {
            StatsItem dataItem = e.Row.DataItem as StatsItem;
            Label lbl = e.Row.FindControl(lblControlName) as Label;
            lbl.Text = string.Format("({0})", dataItem.Count);

            CheckBox cbxGroupName = e.Row.FindControl(cbxControlName) as CheckBox;
            cbxGroupName.Text = dataItem.GroupName;
        }

        protected void ddlMake_OnSelectedIndexChanged(Object sender, EventArgs e)
        {
            PopulateModelsList(Convert.ToInt32(ddlMake.SelectedValue));
        }

        private void UpdateTotalNumOfPosts(int total)
        {
            lblTotalNumber.Text = total.ToString();
            CurrentDisplayListSize = total;
        }

        private void PopulateModelsList(int selectedMakeId)
        {
            ddlModel.Items.Clear();

            // "All" is selected on the Make list
            if (selectedMakeId == GlobalValues.AllMakeId)
            {
                ddlModel.Enabled = false;
            }
            else
            {
                // a make is selected
                IDictionary<int, string> dict = _vehicleInfoService.GetVehicleModels(selectedMakeId);

                AddItemsToDropDownList(ddlModel, dict);

                // add an 'All' item to the list as the first item              
                ddlModel.Items.Insert(0, new ListItem("不限", GlobalValues.AllModelId.ToString()));
                ddlModel.Enabled = true;
            }
        }

        private int GetNumOfCheckedCheckBox(GridView gridView)
        {
            int result = 0;
            foreach (GridViewRow row in gvwGroupByMakes.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox checkBox = row.FindControl("cbxGroupName") as CheckBox;
                    if (checkBox != null && checkBox.Checked)
                    {
                        ++result;
                    }
                }
            }

            return result;
        }

        private int GetTotalNumberPage(int numOfPosts, int postPerPage)
        {
            int retVal = numOfPosts / postPerPage;

            if (numOfPosts % postPerPage > 0)
            {
                retVal++;
            }

            return retVal;
        }
    }
}